package de.gwtprime.client.widgets;

import com.google.gwt.core.shared.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.web.bindery.requestfactory.shared.EntityProxy;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.Request;
import com.google.web.bindery.requestfactory.shared.ServerFailure;

import de.gwtprime.client.ClientFactory;
import de.gwtprime.client.PrimeReceiver;
import de.gwtprime.client.PrimeRequestFactory;
import de.gwtprime.client.event.ApplyTabHeightEvent;
import de.gwtprime.client.event.ArticleSectionOnTypeEvent;
import de.gwtprime.client.event.ArticleSectionPostedEvent;
import de.gwtprime.client.util.HasTextTitleAndProxy;
import de.gwtprime.client.widgets.util.UploadWidget;
import de.gwtprime.shared.requestFactory.ArticleProxy;
import de.gwtprime.shared.requestFactory.ArticleSectionProxy;
import de.gwtprime.shared.requestFactory.request.ArticleRequest;
import de.gwtprime.shared.requestFactory.request.ArticleSectionRequest;

public class ArticleSectionEditWidget extends Composite implements HasTextTitleAndProxy {

	interface ArticleSectionEditWiddgetUiBinder extends UiBinder<Widget, ArticleSectionEditWidget>{}
	ArticleSectionEditWiddgetUiBinder uiBinder = GWT.create(ArticleSectionEditWiddgetUiBinder.class);

	@UiField TextBox sectionTitle;
	@UiField TextArea sectionText;
	
	@UiField Button addSection;
	@UiField SimplePanel uploadWidget;
	boolean newSection = false;
	private final ClientFactory clientFactory;
	private ArticleSectionProxy articleSection;
	
	
	ArticleSectionContentWidget articleSectionContentWidget;
	
	public ArticleSectionEditWidget(final ArticleProxy article, final ClientFactory clientFactory){
		this(null, article, clientFactory, null);
		newSection=true;
		
	}
	
	public ArticleSectionEditWidget(final ArticleSectionProxy articleSection, final ArticleProxy article, final ClientFactory clientFactory, ArticleSectionContentWidget articleSectionContentWidget){
		initWidget(uiBinder.createAndBindUi(this));

		this.articleSectionContentWidget = articleSectionContentWidget;
		this.clientFactory = clientFactory;
		this.articleSection = articleSection;
		sectionText.addKeyUpHandler(new SectionChangeHandler());
		
		sectionTitle.addKeyUpHandler(new SectionChangeHandler());
		
		
		if(articleSection != null){
			sectionText.setText(articleSection.getText());
			sectionTitle.setText(articleSection.getTitle());
		}
		addSection.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				ArticleSectionEditWidget.this.setVisible(false);
				
				if (!newSection) {
					updateExistingArticleSection(clientFactory, articleSection, article);
				} else {
					createNewArticleSection(clientFactory, articleSection, article);
				}
				
				clientFactory.getEventBus().fireEvent(new ApplyTabHeightEvent());
			
			}
		});
		
		
		uploadWidget.add(new UploadWidget(clientFactory, this));
	}
	
	public void updateExistingArticleSection(ClientFactory clientFactory, ArticleSectionProxy articleSection, ArticleProxy article){

		
		// clear the comments and sections because they cause a lot of lookups
		// TODO better solution?
		article.getComments().clear();
		article.getSections().clear();
		
		final PrimeRequestFactory requestFactory = clientFactory.getRequestFactory();
		final ArticleSectionRequest request = requestFactory.articleSectionRequest();
		ArticleSectionProxy articleSectionNew = request.edit(articleSection);
		articleSectionNew.setText(sectionText.getText());
		articleSectionNew.setTitle(sectionTitle.getText());

		Request<Long> createReq2 = request.persist().using(articleSectionNew);

		createReq2.fire(new PrimeReceiver<Long>(clientFactory));
		
		articleSectionContentWidget.setArticleSection(articleSectionNew);
	}
	
	public void createNewArticleSection(final ClientFactory clientFactory, ArticleSectionProxy articleSection, ArticleProxy article){
		
		article.getComments().clear();
		article.getSections().clear();
		final PrimeRequestFactory requestFactory = clientFactory.getRequestFactory();
		final ArticleRequest request = requestFactory.articleRequest();
		
		final ArticleSectionProxy articleSectionNew = request
					.create(ArticleSectionProxy.class);
		
		
		articleSectionNew.setText(sectionText.getText());
		articleSectionNew.setTitle(sectionTitle.getText());

		Request<Void> createReq2 = request.addSectionAndPersist(
				articleSectionNew).using(article);
		
		
		createReq2.fire(new Receiver<Void>() {
			@Override
			public void onSuccess(Void list) {
				System.out.println("success"); // TODO
				clientFactory.getEventBus().fireEvent(new ArticleSectionPostedEvent(articleSectionNew));
			}

			@Override
			public void onFailure(ServerFailure error) {
				System.out.println("failed"); // TODO
			}
		});
		
	}
		
	class SectionChangeHandler implements KeyUpHandler{

		@Override
		public void onKeyUp(KeyUpEvent event) {
			clientFactory.getEventBus().fireEvent(new ArticleSectionOnTypeEvent(articleSection == null ? null : articleSection.getId(), sectionTitle.getText(), sectionText.getText(), articleSection.getImages()));			
		}
	}

	@Override
	public String getText() {
		return sectionText.getText();
	}

	@Override
	public void setText(String text) {
		sectionText.setText(text);
		
	}

	@Override
	public void setTitle(String title) {
		sectionTitle.setTitle(title);
		
	}
	
	@Override
	public String getTitleString() {
		return sectionTitle.getTitle();
	}

	@Override
	public <T extends EntityProxy> void setProxy(T entity) {
		articleSection = (ArticleSectionProxy) entity;
		
	}

	@SuppressWarnings("unchecked")
	@Override
	public ArticleSectionProxy getProxy() {
		return articleSection;
	}


	/**
	 * Handle updated images (image uploaded) -> Save image links
	 */
	@Override
	public void setImages(final String images) {
		ArticleSectionRequest request = clientFactory.getRequestFactory().articleSectionRequest();
		
		request.findArticleSection(articleSection.getId()).fire(new Receiver<ArticleSectionProxy>() {

			@Override
			public void onSuccess(ArticleSectionProxy response) {
				ArticleSectionRequest request = clientFactory.getRequestFactory().articleSectionRequest();
				response = request.edit(response);
				response.setImages(images);
				request.persist().using(response).fire();
				
				articleSection = response;
				
			}
		});
		
	}

	@Override
	public String getImages() {
		return articleSection.getImages();
	}
	
	@Override
	public void updateTextAndImages(String images, String text){
		setText(text);
		clientFactory.getEventBus().fireEvent(new ArticleSectionOnTypeEvent(articleSection == null ? null : articleSection.getId(), getTitleString(), text, images));	
	}
}